//监听屏幕大小变化
$(window).resize(function () {
    // adjustViewContainerSize();
});
var viewerCollection = new Array();
var MaxViewerNum = 15;
var Column = 1;
var Row = 1;
var splitType = "";
//选择布局
function setLayout(val) {
    if (splitType != "layout_style_1") {
        layout(1, 1);
    }
    splitType = val;
    if (val === 'layout_style_1') { //单屏
        layout(1, 1);
    } else if (val === 'layout_style_2') { //横向双屏
        layout(2, 1);
    } else if (val === 'layout_style_3') { //纵向双屏
        layout(1, 2);
    } else if (val === 'layout_style_4') { //横向三屏
        layout(3, 1);
    } else if (val === 'layout_style_5') { //纵向三屏
        layout(1, 3);
    } else if (val === 'layout_style_6') { //2×2四屏
        layout(2, 2);
    } else if (val === 'layout_style_7') { //横向四屏
        layout(4, 1);
    } else if (val === 'layout_style_8') { //纵向四屏
        layout(1, 4);
    }
}

//设置布局
function layout(_Column, _Row, viewNum) {
    if (!viewNum) {
        viewNum = MaxViewerNum;
    }
    //设置全局行列数，用于控制窗口尺寸
    Column = _Column;
    Row = _Row;

    var supply = viewerCollection.length;
    var demand = Column * Row;
    var gap = demand - supply;
    if (gap > 0) {
        for (var i = 0; i < gap; i++) {
            addViewer();
        }
    } else {
        gap = -gap;
        for (var i = 0; i < gap; i++) {
            removeViewer(viewerCollection.pop());
        }
        //调整窗口布局及相关元素位置
        // adjustViewContainerSize();
        $("#cesiumContainer").css("width", "100%");
    }
}

//控制单个视窗大小
function adjustViewContainerSize() {
    var width = $(document.body).width();
    var height = $(document.body).height();
    var single_width = width / Column - 2;
    var single_height = height / Row - 2;
    $('.cesiumContainer').width(single_width);
    $('.cesiumContainer').height(single_height);
}

//添加视图
function addViewer() {
    if (viewerCollection.length > MaxViewerNum) {
        alert("允许最大视窗数量为" + MaxViewerNum + "个");
        return;
    }

    var divId = "viewer" + viewerCollection.length;
    var containerWidth = $("#cesiumContainer").width() / 2;
    var Odiv = document.createElement("div");
    Odiv.id = divId;
    Odiv.className = "cesiumContainer";
    Odiv.style = "position:absolute;right:0px;height: 100%;width:50% !important;border-left: 2px solid #0b00ffd6;";

    document.getElementById("cesiumContainer").parentElement.appendChild(Odiv);
    // $("body").append("<div id=" + divId + " class='cesiumContainer' style='position:absolute;right:0px;'></div>");
    $("#cesiumContainer").css("width", "50%");
    var viewer22 = createViewer(divId);
    viewer22.id = divId;
    viewer22.master = viewerCollection.length == 0 ? true : false;
    viewerCollection.push(viewer22);

    //添加监听master
    $('#' + divId).hover(function () {
        for (v in viewerCollection) {
            if (viewerCollection[v].id === divId) {
                viewerCollection[v].master = true;
            } else {
                viewerCollection[v].master = false;
            }
        }
    });
}

//创建一个视图
function createViewer(divId) {
    var viewer22 = new Cesium.Viewer(divId, {
        timeline: false,
        animation: false,
        navigationHelpButton: false,
        sceneMode: Cesium.SceneMode.SCENE3D,
        sceneModePicker: false,
        baseLayerPicker: false,
        mapMode2D: Cesium.MapMode2D.ROTATE, //2D地图可以在水平方向无限滚动
        vrButton: false, //VR
        navigation: false,
        terrainExaggeration: 1, //地形高程比例
        shadows: false, //确定阴影是否由太阳投下
        terrainShadows: Cesium.ShadowMode.DISABLED, //确定地形是否投射或接收来自太阳的阴影
        timeline: false, //时间线
        navigationHelpButton: false, //使用帮助
        geocoder: false, //地理编码
        homeButton: false,
        selectionIndicator: false,
        infoBox: false
    });
    //复制三维球图层到新三维球
    viewer22.scene.imageryLayers._layers = [];
    for (var i = 0 ; i < viewer.imageryLayers._layers.length ; i++) {
        viewer22.scene.imageryLayers.addImageryProvider(viewer.imageryLayers._layers[i].imageryProvider)
    }
    //复制模型
    for (var i = 0 ; i < viewer.scene.primitives._primitives.length ; i++) {
        viewer22.scene.primitives.add(new Cesium.Cesium3DTileset({
            url: viewer.scene.primitives._primitives[i].url,
            maximumMemoryUsage: 2048//tileset可以使用的最大内存量（以MB为单位）,默认512。
            // minimumPixelSize: 128,
            // maximumScale: 20000
            // maximumScreenSpaceError: 4, //最大屏幕空间误差
            //maximumNumberOfLoadedTiles: 100000 //最大加载瓦片个数
        }));
        // viewer22.scene.primitives.add(viewer.scene.primitives._primitives[i]);
    }
    //复制地形
    if (viewer.scene.terrainProvider) {
        viewer22.scene.terrainProvider = viewer.scene.terrainProvider;
    }
    //复制实体
    for (var i = 0 ; i < viewer.entities._entities.values.length ; i++) {
        viewer22.entities.add(viewer.entities._entities.values[i])
    }
    viewer22.scene.postProcessStages.fxaa.enabled = true; //是否开启抗锯齿
    viewer22.scene.fxaa = true;//是否开启抗锯齿
    viewer22.scene.fog.enabled = false;//去除云雾效果
    viewer22.scene.skyAtmosphere.show = !1;
    // viewer22.scene.globe.baseColor = Cesium.Color.BLACK;
    return viewer22;
}

//根据id获取一个视图
function getViewerById(_id) {
    for (v in viewerCollection) {
        if (viewerCollection[v].id == _id)
            return viewerCollection[v];
    }
    console.warn('Can not find viewer which id is ' + _id);
    return null;
}

//获取激活状态的viewer
function getActiveViewer() {
    for (v in viewerCollection) {
        if (viewerCollection[v].master) {
            return viewerCollection[v];
        }
    }
    return null;
}

//移除一个视图
function removeViewer(viewer22) {
    $('#' + viewer22.id).remove()
    viewer22.destroy();
}

//视角同步
function viewSync() {
    //获取主视图相机姿态
    var viewCfg;
    for (v in viewerCollection) {
        if (viewerCollection[v].master) {
            if (viewerCollection[v].scene.mode === Cesium.SceneMode.MORPHING)
                return;
            viewCfg = getCameraCondition(viewerCollection[v]);
            break;
        }
    }

    //同步其它相机
    for (v in viewerCollection) {
        if (!viewerCollection[v].master && viewerCollection[v].scene.mode !== Cesium.SceneMode.MORPHING) {
            viewerCollection[v].camera.setView(viewCfg);
        }
    }
}

// 获得相机姿态
function getCameraCondition(master) {
    if (master.scene.mode === Cesium.SceneMode.SCENE3D) {
        const positionDest = master.scene.camera.positionWC.clone()
        return {
            destination: positionDest.clone(),
            endTransform: master.camera.endTransform,
            orientation: {
                heading: master.scene.camera.heading,
                pitch: master.scene.camera.pitch,
                roll: master.scene.camera.roll
            }
        }
    } else {
        const cartographicDest = master.scene.camera.positionCartographic.clone();
        const positionDest = master.scene.mapProjection.ellipsoid.cartographicToCartesian(cartographicDest);
        return {
            destination: positionDest.clone()
        }
    }
}

//生成区间内随机整数
function getRandom(max, min) {
    var rand = false;
    rand = Math.floor(Math.random() * max);
    if (!(min == undefined) && (max >= min)) {
        rand = Math.floor(Math.random() * (max - min) + min);
    } else if (max < min) {
        return false;
    }
    return rand;
}